const orderPrefix = 'order-'
const orderExpire = 30 * 60 * 1000

function getCacheId(id: number | string): string {
  return `${orderPrefix}${id}`
}

export function cacheOrder(id: number | string, data: object) {
  // console.log(id,data)
  // clearCacheOrder()
  const cacheId = getCacheId(id)
  const value = JSON.stringify({
    expired: Date.now() + orderExpire,
    data: data,
  })
  localStorage[cacheId] = value
}

export function getCacheOrder(id: number | string): object {
  const cacheId = getCacheId(id)

  return JSON.parse(localStorage[cacheId] || '{}').data
}

export function clearCacheOrder() {
  const len = localStorage.length
  for (let i = 0; i < len; i++) {
    const key = localStorage.key(i) as string
    if (key.indexOf(orderPrefix) > -1) {
      const value = JSON.parse(localStorage[key])
      if (value.expired < Date.now()) {
        localStorage.removeItem(key)
      }
    }
  }
}
